package com.booksystem.campuslibrarymanagementsystem.controller.user;


import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.BookReturnrequst.DeletBorrowReturn;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.BookReturnrequst.Returnbook;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.BookReturnrequst.Returnbooklist;
import com.booksystem.campuslibrarymanagementsystem.commen.request.userquest.BookReturnrequst.Returnbookliststatus;
import com.booksystem.campuslibrarymanagementsystem.commen.result.Result;
import com.booksystem.campuslibrarymanagementsystem.commen.result.userresuilt.ReturnTable;
import com.booksystem.campuslibrarymanagementsystem.entity.BorrowApprovalsTable;
import com.booksystem.campuslibrarymanagementsystem.entity.ReturnrequesTable;
import com.booksystem.campuslibrarymanagementsystem.service.ReturnrequesTableService;
import com.booksystem.campuslibrarymanagementsystem.utils.JwtUtil;
import com.booksystem.campuslibrarymanagementsystem.utils.TimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RequestMapping("/User")
@Api(tags = "图书归还")
@RestController
public class BookReturnController {


    @Autowired
    ReturnrequesTableService returnrequesTableService;

    /*
    图书归还

     */
    @PostMapping("/bookreturn")
    @ApiOperation(value = "图书归还",notes = "通过账户id,图书id进行归还图书，")
    public Result BookReturn (@RequestBody Returnbook returnbook){
        Map<String, Object> parsed = JwtUtil.tokenPre(returnbook.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int bookid =returnbook.getBookid();//图书id
                String time = TimeUtil.getTime();//自动生成归还时间
                //通过图书id查询该图书是否被借阅，没有则不能归还图书
                //通过图书id查询该图书是否借阅，查看借阅状态通过没有，通过则可进行归还，未通过表示该图书没有被借阅，不能归还
                //如果有两个借阅记录，只要有一个借阅通过都可以归还
                List<BorrowApprovalsTable> dd = returnrequesTableService.ddd((String) account,bookid);
                if (dd.isEmpty()) {
                    return Result.fail("该图书没有被借阅，不能进行归还图书？");
                }
                // 检查是否存在至少一个状态为“已通过”的记录
                boolean hasApprovedRecord = false;
                for (BorrowApprovalsTable record : dd) {
                    if ("已通过".equals(record.getApprovalstate())) {
                        hasApprovedRecord = true;
                        break; // 一旦找到一个已通过的记录，立即退出循环
                    }
                }
                if (!hasApprovedRecord) {
                    // 没有找到已通过的记录
                    return Result.fail("不存在已通过的借阅图书记录，无法进行归还图书。");
                }
                // 检查该用户是否已经归还了这本书，并且归还状态为“已通过”
//                            List<ReturnrequesTable> existingBorrow = returnrequesTableService.existsByAccountAndBookidi((String) account, bookid);
//                            if (existingBorrow != null && !existingBorrow.isEmpty()) {
//                                for (ReturnrequesTable entry : existingBorrow) {
//                                    if ("已通过".equals(entry.getApprovalstate())) {//已通过
//                                        break; // 退出循环
//                                    } else {
//                                        // 如果归还记录还未过期，不允许再次归还
//                                        return Result.fail(String.format("您已经归还过这本书：%s", bookid));
//                                    }
//                                }
//                            }
                // 检查该用户是否已经归还了这本书，并且归还状态为“已通过”
                List<ReturnrequesTable> existingBorrow = returnrequesTableService.existsByAccountAndBookidi((String) account, bookid);
                if (existingBorrow != null && !existingBorrow.isEmpty()) {
                    for (ReturnrequesTable entry : existingBorrow) {
                        if ("已通过".equals(entry.getApprovalstate())) { // 已通过
                            return Result.fail(String.format("您已经归还过这本书：%s", bookid));
                        }
                    }
                }

                ReturnrequesTable cc = new ReturnrequesTable();
                cc.setAccount((String) account);
                cc.setBookid(bookid);
                cc.setReturndate(time);
                cc.setApprovalstate("未通过");

                int a = returnrequesTableService.add(cc);
                if (a>0) {
                    return Result.success(cc,1);
                } else {
                    return Result.fail((String.format("该账户归还失败：%s,请重新归还",(String) account)));
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }


    /*
    图书归还列表
    通过归还用户id查看所有归还列表
     */
    @PostMapping("/bookreturnlist")
    @ApiOperation(value = "图书归还列表", notes = "查看所有归还列表")

    public Result<List<ReturnTable>> selectBookreturn (@RequestBody Returnbooklist returnbooklist){
        Map<String, Object> parsed = JwtUtil.tokenPre(returnbooklist.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                //根据归还账户id查询所有归还列表
                List<ReturnTable>  hhh = returnrequesTableService.returnlist((String) account);
                if (hhh.isEmpty()) {
                    return Result.fail("该归还账户id没有进行归还图书，可以去归还？");
                } else {
                    return Result.success(hhh,1);
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }

    }

    /*
   通过判断状态（未通过，通过）
   可以查看所有未通过的列表和所有通过列表
    */
    @PostMapping("/booklisttstatus")
    @ApiOperation(value = "是否通过,拒绝的图书归还列表", notes = "可以查看所有未通过的列表和所有通过的归还图书列表")
    public Result<List<ReturnTable>> selectBookstatuslist (@RequestBody Returnbookliststatus returnbookliststatus) {
        Map<String, Object> parsed = JwtUtil.tokenPre(returnbookliststatus.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                // String Account = returnbookliststatus.getAccount();
                String statu = returnbookliststatus.getApprovalstate();
                // 判断状态是否为空
                if (statu == null || statu.trim().isEmpty()) {
                    //根据归还账户id查询所有归还列表
                    List<ReturnTable>  hhh = returnrequesTableService.returnlist((String) account);
                    if (hhh.isEmpty()) {
                        return Result.fail("该归还账户id没有归还图书，请重新搜索？");
                    } else {
                        return Result.success(hhh,1);
                    }
                }

                List<ReturnTable> statusList = null;
                if ("已通过".equals(statu)) {
                    statusList = returnrequesTableService.returnliststatus((String) account,statu);
                } else if ("未通过".equals(statu)) {
                    statusList = returnrequesTableService.returnliststatus((String) account,statu);
                }else if ("未审批".equals(statu)) {
                    statusList = returnrequesTableService.returnliststatus((String) account,statu);
                }else {
                    return Result.fail("无效的状态值");
                }

                // 检查列表是否为空
                if (statusList.isEmpty()) {
                    return Result.fail("没有找到账户id为 '" +(String) account + "状态为 '"+ statu + "' 的归还记录");
                } else {
                    return Result.success(statusList, statusList.size());
                }
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }

    @PostMapping("/deleteBookReturn")
    @ApiOperation(value = "删除归还记录",notes = "账户id，归还id进行删除该账户下该图书的归还记录")
    public Result deleteBookRenew(@RequestBody DeletBorrowReturn deletBorrowReturn) {
        Map<String, Object> parsed = JwtUtil.tokenPre(deletBorrowReturn.getToken());
        if (parsed != null) {
            Object identity = parsed.get("identity");
            Object account = parsed.get("account");
            if (identity.equals("user")) {
                int  bookid =deletBorrowReturn.getReturnid();  //归还id
                int hh = returnrequesTableService.deleteByAccountAndBookid((String) account, bookid);
                // 首先检查该用户是否已经续借了这本书
                if (hh>0) {
                    return  Result.success("成功删除该图书归还记录",1);
                }
                return Result.fail(String.format("没有该图书的归还记录：%s", bookid));
            } else {
                return Result.fail("身份权限不足");
            }
        } else {
            return Result.fail("请输入正确token值");
        }
    }

}
